package com.binfenhulian.chinaenergy.ces.manage.framework.interceptor;

import com.binfenhulian.chinaenergy.ces.manage.bean.param.SessionParam;
import com.binfenhulian.chinaenergy.ces.manage.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Created by wanghjbuf on 2018/3/8.
 */
@Slf4j
public class ManageLoginCheckInterceptor extends HandlerInterceptorAdapter {

    /**
     * 权限前置判断
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws IOException
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        HttpSession session = request.getSession();
        final HandlerMethod handlerMethod = (HandlerMethod) handler;
        final Method method = handlerMethod.getMethod();
        final Class<?> clazz = method.getDeclaringClass();
        if (clazz.isAnnotationPresent(ManageLoginCheck.class) || method.isAnnotationPresent(ManageLoginCheck.class)) {

            SessionParam sp = (SessionParam) session.getAttribute(Constants.MANAGE_SESSION_KEY);
            if (sp == null) {
                // 未登录状态
                String query = request.getQueryString();
                String uri = request.getRequestURI();
                String returnUrl;
                if (query != null) {
                    returnUrl = uri + "?" + query;
                } else {
                    returnUrl = uri;
                }
                returnUrl = "/manage/login.html";
                response.setContentType("application/json; charset=UTF-8");
                response.setStatus(200);
//                IOUtils.write("{\"code\": \"1009\",\"message\": \"请先登录\",\"data\":\"" + returnUrl + "\", \"status\":false}", response.getWriter());
                response.sendRedirect(returnUrl);
                return false;
            }

            request.setAttribute("ACCOUNT_NAME", sp.getName());
            return true;
        }
        return true;
    }
}
